package com.learn.designPatterns.createType.builder;

import java.util.Arrays;

/**
 * @classname:
 * @Description:
 * @author: yfpu
 * @Date: 2018-09-10 19:39
 */
public class AbstractStringBuilder {
    protected int count;
    protected char[] value;

    public AbstractStringBuilder(int capacity) {
        value = new char[capacity];
        this.count = 0;
    }

    public AbstractStringBuilder append(char a) {
        ensureCapacityInternal(count + 1);
        value[count++] = a;
        return this;
    }

    private void ensureCapacityInternal(int miniNumCapacity) {
        // overflow-conscious code
        if (miniNumCapacity > value.length)
            expandCapacity(miniNumCapacity);
    }

    void expandCapacity(int miniNumCapacity) {
        int newCapatity = value.length * 2 + 2;

        if (newCapatity < miniNumCapacity)
            newCapatity = miniNumCapacity;

        if (newCapatity < 0) {

            if (miniNumCapacity < 0)// overflow
                throw new OutOfMemoryError();
            newCapatity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapatity);

    }
}
